<template>
    <div class="container">
        <div class="header">
            <el-button type="primary" size="mini" @click="refreshStatic">刷新</el-button>
            <el-button type="primary" size="mini" @click="queryStatic">查询</el-button>
            <el-button type="primary" size="mini" v-authCode.show="B_0153" @click="loadout">导出</el-button>
            <el-button type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
        </div>
        <div class="dataInfo">
            <div>
                <vxe-table
                    style="width: 100%"
                    :auto-resize="true"
                    resizable
                    show-overflow
                    border
                    stripe
                    ref="xTable"
                    :data="tableDataResult"
                    @sort-change="handleSort"
                    :expand-config="{ iconOpen: 'el-icon-remove', iconClose: 'el-icon-circle-plus', toggleMethod }"
                    :sort-config="{
                        defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                        remote: true,
                    }"
                    highlight-hover-row
                    :key="tableDataResultNumKey + 'tableDataResultNumKey'"
                    v-loading="tableDataResultLoading"
                    header-align="center"
                    show-header-overflow
                >
                    <!-- 子表格 -->
                    <vxe-table-column type="expand" width="50px">
                        <template #content="{ row:parentRow,rowIndex:parentIndex }">
                            <div v-if="parentRow.children && parentRow.children.length > 0">
                            <div class="expand-wrapper">
                            <vxe-table :data="getPage(parentRow.children)"
                                       :scroll-y="50"
                                       show-header-overflow
                                       :auto-resize="true"
                                       resizable
                                       @checkbox-all="selectAllValueEvent"
                                       @checkbox-change="selectValueChangeEvent">
                                <vxe-table-column type="checkbox" width="40" fixed="left"></vxe-table-column>
                                <vxe-column
                                    show-overflow="tooltip"
                                    v-for="item in showFieldList"
                                    :fixed="item.type === 'btn' ? (item.fixed ? item.fixed : 'right') : ''"
                                    :key="item.id"
                                    :width="item.width || ''"
                                    :min-width="item.minWidth || '100'"
                                    :title="item.content"
                                    :field="item.id"
                                    :sortable="!['reportCode', 'reportName', 'marketName'].includes(item.id)"
                                    header-align="center"
                                    :align="getAlign(item)"
                                >
                                    <template #default="{ row }">
                            <span v-if="item.type == 'func'">
                                {{ item.funcBody(row[item.id], row) || '--' }}
                            </span>
                                        <span v-else-if="item.type == 'statusTag'">
                                <StatusTag :code="row[item.id]"></StatusTag>
                            </span>
                                        <span v-else-if="item.type == 'status'">
                                {{ item.statusKV[row[item.id]] }}
                            </span>
                                        <span v-else-if="item.type == 'date'">
                                {{ dateFormat(row[item.id]) || '--' }}
                            </span>

                                        <span v-else-if="item.id == 'dictStockCodes'" :key="fieldKey + 'dictStockCodes'">
                                <el-tooltip placement="bottom" popper-class="tips-popper">
                                    <div slot="content" v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length > 1">
                                        <div v-for="(item, index) in row.dictStockCodes" :key="index">
                                            {{ item.dictKey + '(' + item.dictKeyName + ')' }}
                                        </div>
                                    </div>

                                    <el-tag v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length > 1" style="cursor: default">
                                        {{ row.dictStockCodes.length + '个证券' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length === 1">
                                    {{ row.dictStockCodes[0].dictKey + '(' + row.dictStockCodes[0].dictKeyName + ')' }}
                                </span>
                                <span
                                    v-if="
                                        !row.hasOwnProperty('dictStockCodes') ||
                                        (row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length === 0)
                                    "
                                >
                                    --
                                </span>
                            </span>
                                        <span v-else-if="item.id == 'branchValues'" :key="fieldKey + 'branchValues'">
                                <el-tooltip placement="bottom">
                                    <div slot="content" v-if="row.hasOwnProperty('branchValues') && row.branchValues.length > 1">
                                        <div v-for="(item, index) in row.branchValues" :key="index">
                                            {{ item.replace(/(\.|\d+)$/, $1 => numberFormat($1)) }}
                                        </div>
                                    </div>
                                    <el-tag v-if="row.hasOwnProperty('branchValues') && row.branchValues.length > 1" style="cursor: default">
                                        {{ row.branchValues.length + '个分支' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('branchValues') && row.branchValues.length === 1">{{
                                        row.branchValues[0].replace(/(\.|\d+)$/, $1 => numberFormat($1))
                                    }}</span>
                            </span>
                                        <span v-else-if="item.id == 'investBalance'" :key="fieldKey + 'investBalance'">
                                <span v-if="!row.investBalance || !row.investBalance.trim()"></span>
                                <el-popover
                                    v-else-if="getObjectLength(JSON.parse(row.investBalance)) && getObjectLength(JSON.parse(row.investBalance)) > 1"
                                    placement="top"
                                    trigger="hover"
                                >
                                    <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in JSON.parse(row.investBalance)" :key="key">
                                        {{ '阀值' + ++index + '可投余量: ' + JSON.parse(row.investBalance)['INVESTABLE_BALANCE_' + index] }}
                                    </div>
                                    <el-tag slot="reference">{{ getObjectLength(JSON.parse(row.investBalance)) + '个可投余量' }}</el-tag>
                                </el-popover>
                                <span v-else v-for="(value, key) in JSON.parse(row.investBalance)" :key="key">{{ value }}</span>
                            </span>
                                        <span v-else>
                                {{ row[item.id] === 0 || (row[item.id] && (row[item.id] + '').trim()) ? row[item.id] : '--' }}
                            </span>
                                    </template>
                                </vxe-column>
                                <vxe-table-column title="操作" show-overflow width="150" fixed="right" align="center">
                                    <template #default="{ row }">
                                        <RiskIconButton type="primary" topTitle="详情" icon="el-icon-view" @on-click="handleRowOperateLook(row)"></RiskIconButton>
                                        <RiskIconButton
                                            icon="el-icon-data-analysis"
                                            type="primary"
                                            topTitle="走势图"
                                            @on-click="handleRowOperateChart(row)"
                                        ></RiskIconButton>
                                    </template>
                                </vxe-table-column>
                            </vxe-table>
                            </div>
                            <RiskPagination :paging="page1" @page-change="currentChange(parentRow.children)"></RiskPagination>
                            </div>
                            <div v-else class="expand-wrapper"></div>
                        </template>
                    </vxe-table-column>
<!--                    <vxe-table-column type="checkbox" min-width="40" fixed="left"></vxe-table-column>-->
                    <vxe-column
                        v-for="item in sumColumns"
                        :fixed="item.type === 'btn' ? (item.fixed ? item.fixed : 'right') : ''"
                        :key="item.id"
                        :width="item.width || ''"
                        :min-width="item.minWidth || '100'"
                        :title="item.content"
                        :field="item.id"
                        :sortable="!['reportCode', 'reportName', 'marketName'].includes(item.id)"
                        header-align="center"
                        :align="getAlign(item)"
                    >
                        <template #default="{ row }">
                            <span v-if="item.type == 'func'">
                                {{ item.funcBody(row[item.id], row) || '--' }}
                            </span>
                            <span v-else-if="item.type == 'statusTag'">
                                <StatusTag :code="row[item.id]"></StatusTag>
                            </span>
                            <span v-else-if="item.type == 'status'">
                                {{ item.statusKV[row[item.id]] }}
                            </span>
                            <span v-else-if="item.type == 'date'">
                                {{ dateFormat(row[item.id]) || '--' }}
                            </span>

                            <span v-else-if="item.id == 'dictStockCodes'" :key="fieldKey + 'dictStockCodes'">
                                <el-tooltip placement="bottom" popper-class="tips-popper">
                                    <div slot="content" v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length > 1">
                                        <div v-for="(item, index) in row.dictStockCodes" :key="index">
                                            {{ item.dictKey + '(' + item.dictKeyName + ')' }}
                                        </div>
                                    </div>

                                    <el-tag v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length > 1" style="cursor: default">
                                        {{ row.dictStockCodes.length + '个证券' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length === 1">
                                    {{ row.dictStockCodes[0].dictKey + '(' + row.dictStockCodes[0].dictKeyName + ')' }}
                                </span>
                                <span
                                    v-if="
                                        !row.hasOwnProperty('dictStockCodes') ||
                                        (row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length === 0)
                                    "
                                >
                                    --
                                </span>
                            </span>
                            <span v-else-if="item.id == 'branchValues'" :key="fieldKey + 'branchValues'">
                                <el-tooltip placement="bottom">
                                    <div slot="content" v-if="row.hasOwnProperty('branchValues') && row.branchValues.length > 1">
                                        <div v-for="(item, index) in row.branchValues" :key="index">
                                            {{ item.replace(/(\.|\d+)$/, $1 => numberFormat($1)) }}
                                        </div>
                                    </div>
                                    <el-tag v-if="row.hasOwnProperty('branchValues') && row.branchValues.length > 1" style="cursor: default">
                                        {{ row.branchValues.length + '个分支' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('branchValues') && row.branchValues.length === 1">{{
                                    row.branchValues[0].replace(/(\.|\d+)$/, $1 => numberFormat($1))
                                }}</span>
                            </span>
                            <span v-else-if="item.id == 'investBalance'" :key="fieldKey + 'investBalance'">
                                <span v-if="!row.investBalance || !row.investBalance.trim()"></span>
                                <el-popover
                                    v-else-if="getObjectLength(JSON.parse(row.investBalance)) && getObjectLength(JSON.parse(row.investBalance)) > 1"
                                    placement="top"
                                    trigger="hover"
                                >
                                    <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in JSON.parse(row.investBalance)" :key="key">
                                        {{ '阀值' + ++index + '可投余量: ' + JSON.parse(row.investBalance)['INVESTABLE_BALANCE_' + index] }}
                                    </div>
                                    <el-tag slot="reference">{{ getObjectLength(JSON.parse(row.investBalance)) + '个可投余量' }}</el-tag>
                                </el-popover>
                                <span v-else v-for="(value, key) in JSON.parse(row.investBalance)" :key="key">{{ value }}</span>
                            </span>
                            <span v-else>
                                {{ row[item.id] === 0 || (row[item.id] && (row[item.id] + '').trim()) ? row[item.id] : '--' }}
                            </span>
                        </template>
                    </vxe-column>
                </vxe-table>
            </div>
            <RiskPagination :paging="page" @page-change="pageQuery"></RiskPagination>
        </div>
        <StaticResultDetailSearch
            v-if="staticResultQueryDialogVO.visible"
            :staticResultQueryDialogVO="staticResultQueryDialogVO"
            :reqVO="staticResultReqVO"
            @staticResultQueryReturn="staticResultQueryReturn"
            :editableTabsValue="activeValue"
            :isHistory="isHistory"
            :showErrorType="showErrorType"
        >
        </StaticResultDetailSearch>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="!this.isHistory ? columns : historyColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :table-name="!this.isHistory ? 'RISK_RES' : 'RISK_RESULT_H'"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import Dict from '@/pages/static/dict/index.ts';
import { getCurrentPageData, numberFormat, formatterDate, formatterTime, formatter, formatterNumber,
    unitShow,
    dateFormat,
    thousandsFormat,
    timeFormat,
    getConfigItem,
    numberFormatXDAY,
} from '@/utils/tools';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import StaticResultDetail from '@/pages/static/risk-result/static-result-detail.vue';
import StaticResultSearch from '@/pages/static/risk-result/static-result-search.vue';
import ColumnUtil from '@/pages/risk-time/utils/column-util';
import { downLoadFile } from '@/utils/request';
import { getTableLayout } from '@/common/api/commonApi';
import { DialogVO } from '@yhfin/biz';
import { getSystem } from '@/utils/user-util';
import DictionConstUtil from '@/utils/diction-const-util';
import StaticResultDetailSearch from '@/project/fscinda/pages/risk-result/static-result-detail-search.vue';

@Component({
    name: 'RiskResultSumDetail',
    components: {
        StaticResultDetailSearch,
        RiskIconButton,
        StaticResultSearch,
        StaticResultDetail,
        StatusTag,
        BranchTag,
        RiskTableLayout,
        RiskPagination,
    },
})
export default class RiskResultSumDetail extends Vue {
    @Prop() activeValue: string;
    @Prop() assetList: any;
    @Prop() fdAcList: any;
    // 详情数据
    @Prop() transToResultDetail;
    // 是否为历史详情
    @Prop() isHistory: boolean;
    getCurrentPageData = getCurrentPageData;
    numberFormat = numberFormat;
    unitShow = unitShow;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    WEB_DOCKING = getConfigItem('WEB_DOCKING');

    sortProp: string = 'triggerType';
    sortOrder: string = 'desc'; // 排序方式

    private page: any = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };
    private page1: any = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };
    showErrorType: boolean = false; // 是否展示错误类型
    private tableDataResultLoading: boolean = false; // 静态结果加载

    // 静态结果请求参数
    private staticResultReqVO: any = {
        calculateDateEnd: '',
        calculateDateStart: '',
        entryCodes: '',
        entryGroups: [],
        entryKey: '',
        entryName: '',
        excludeEntryGroup: false,
        fundGroups: [],
        paging: { total: 0, currentPage: 1, totalPage: 0, pageSize: 50 },
        prohibitionDate: '',
        reBankCode: '',
        reFundCode: '',
        reIssueCode: '',
        reStockCode: '',
        resultId: '',
        showNewRecord: '1',
        tradeDateStart: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        tradeDateEnd: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        triggerTypeList: [],
        precision: false,
        sort: '',
        fundTypes: [],
        fdProductCodes: [],
    };

    // 结果查询参数
    sortParamObj = {
        resultId: 'N_RESULT_ID',
        tradeDate: 'D_TRADE_DATE',
        calculateDate: 'D_CAL_DATE',
        dictFundCodes: 'C_FUND_CODES',
        triggerType: 'C_TRIGGER_TYPE',
        entryName: 'C_ENTRY_NAME',
        result: 'N_RESULT',
        prohibitionDate: 'N_PROHIBITION_DATE',
        triggerDay: 'N_TRIGGER_DAY',
        dictStockCodes: 'LENGTH(C_STOCK_CODES)',
        branchValues: 'C_BR_VALUES',
        compareType: 'C_COMPARE_TYPE',
        thresholdValue: 'N_THRESHOLD_VALUE',
        legalDays: 'N_LEGAL_DAYS',
        insideDays: 'N_INSIDE_DAYS',
        frequency: 'N_FREQUENCY',
        resultInformation: 'length(C_OUTCOME_INFORMATION)',
        investBalance: 'C_INVEST_BALANCE',
        assetCodes: 'LENGTH(C_ASSET_CODES)',
        fdAcCodes: 'LENGTH(C_FD_AC_CODES)',
        errorMessage: 'C_ERROR_MESSAGE',
        fdProductCode: 'C_FD_PRODUCT_CODE',
        fundType: 'C_FUND_TYPE',
        numerator: 'N_NUMERATOR',
        denominator: 'N_DENOMINATOR',
    };

    // 历史结果参数
    historyColumns: any = [
        {
            id: 'tradeDate',
            content: '估值日期',
            type: 'date',
            align: 'center',
            minWidth: 120,
        },
        {
            id: 'calculateDate',
            content: '计算日期',
            type: 'func',
            funcBody: (value, row) => dateFormat(row['calculateDate']) + '\n' + timeFormat(row['calculateTime']),
            align: 'center',
            minWidth: 160,
        },
        {
            id: 'dictFundCodes',
            content: '产品代码(名称)',
            minWidth: 160,
            type: 'func',
            funcBody: value => this.formatDictFundCodes(value),
        },
        {
            id: 'assetCodes',
            content: '资产单元编号(名称)',
            show: this.SHOW_SECURITY,
            minWidth: 170,
            type: 'func',
            funcBody: value => this.formatAssetCodes(value),
        },
        {
            id: 'fdAcCodes',
            content: '组合编码(名称)',
            show: this.SHOW_SECURITY,
            minWidth: 160,
            type: 'func',
            funcBody: value => this.formatFdAcCodes(value),
        },
        {
            id: 'triggerType',
            content: '触警类型',
            type: 'statusTag',
        },
        {
            id: 'entryCode',
            content: '条目编号',
        },
        {
            id: 'entryName',
            content: '风险说明',
            minWidth: 120,
        },
        {
            id: 'result',
            content: '计算结果(单位)',
            type: 'func',
            funcBody: (value, row) => {
                if (this.WEB_DOCKING === 'FSCINDA') {
                    return row.result != undefined ? numberFormatXDAY(row.result, row.unit) + unitShow(row.unit) : '--';
                }
                return row.result != undefined ? numberFormat(row.result, row.unit) + unitShow(row.unit) : '--';
            },
            minWidth: 140,
        },

        {
            id: 'errorMessage',
            content: '计算错误信息',
            minWidth: 160,
            show: this.showErrorType,
        },
        {
            id: 'prohibitionDate',
            content: '连续违规天数',
            align: 'right',
            type: 'func',
            funcBody: (value, row) => (row.prohibitionDate > -1 ? row.prohibitionDate + '天' : '0'),
            minWidth: 140,
        },
        {
            id: 'triggerDay',
            content: '连续触警天数',
            align: 'right',
            type: 'func',
            funcBody: (value, row) => (row.triggerDay > -1 ? row.triggerDay + '天' : ''),
            minWidth: 140,
        },
        {
            id: 'dictStockCodes',
            content: '证券代码(名称)',
            minWidth: 140,
        },
        {
            id: 'reportCode',
            content: '证券代码',
            minWidth: 140,
        },
        {
            id: 'reportName',
            content: '证券名称',
            minWidth: 140,
        },
        {
            id: 'marketName',
            content: '交易市场',
            minWidth: 140,
        },
        {
            id: 'fdProductCode',
            content: '基金代码',
            minWidth: 140,
        },
        {
            id: 'fundType',
            content: '产品类型',
            minWidth: 140,
        },
        {
            id: 'branchValues',
            content: '分支值',
            minWidth: 140,
        },
        {
            id: 'numerator',
            content: '分子值',
            minWidth: 140,
            funcBody: (value, row) => numberFormat(value),
        },
        {
            id: 'denominator',
            content: '分母值',
            minWidth: 140,
            funcBody: (value, row) => numberFormat(value),
        },
        {
            id: 'compareType',
            content: '条目比较方向',
            type: 'status',
            statusKV: Dict.CompareDirection,
            minWidth: 140,
        },
        {
            id: 'thresholdValue',
            content: '条目触发值',
            type: 'func',
            funcBody: (value, row) => (row.thresholdValue != undefined ? numberFormat(row.thresholdValue, row.unit) + unitShow(row.unit) : '--'),
            minWidth: 120,
        },
        {
            id: 'investBalance',
            content: '可投余量',
            align: 'right',
        },
        {
            id: 'controlGrade',
            content: '风险等级',
            minWidth: 120,
            align: 'center',
            type: 'func',
            funcBody: (value, row) => DictionConstUtil.ControlGrade[value] || '--',
        },
    ];

    columns: any[] = [
        {
            id: 'resultId',
            content: '序号',
        },
        {
            id: 'legalDays',
            content: '法定调整天数',
            align: 'right',
            minWidth: 140,
        },
        {
            id: 'insideDays',
            content: '内部调整天数',
            align: 'right',
            minWidth: 140,
        },
        {
            id: 'frequency',
            content: '触发频率次数',
            align: 'right',
            minWidth: 140,
        },
        {
            id: 'resultInformation',
            content: '结果信息',
        },
    ];
  // 外层表头字段
    sumColumns: any = [
        {
            id: 'triggerType',
            content: '触警类型',
            type: 'statusTag',
        },
        {
            id: 'tradeDate',
            content: '估值日期',
            type: 'date',
            align: 'center',
            minWidth: 120,
        },
        {
            id: 'calculateDate',
            content: '计算日期',
            type: 'func',
            funcBody: (value, row) => dateFormat(row['calculateDate']) + '\n' + timeFormat(row['calculateTime']),
            align: 'center',
            minWidth: 160,
        }, {
            id: 'dictFundCodes',
            content: '产品代码(名称)',
            minWidth: 160,
            type: 'func',
            funcBody: value => this.formatDictFundCodes(value),
        }, {
            id: 'entryName',
            content: '风险说明',
            minWidth: 120,
        }, {
            id: 'compareType',
            content: '条目比较方向',
            type: 'status',
            statusKV: Dict.CompareDirection,
            minWidth: 140,
        },
        {
            id: 'thresholdValue',
            content: '条目触发值',
            type: 'func',
            funcBody: (value, row) => (row.thresholdValue != undefined ? numberFormat(row.thresholdValue, row.unit) + unitShow(row.unit) : '--'),
            minWidth: 120,
        }, {
            id: 'legalDays',
            content: '法定调整天数',
            align: 'right',
            minWidth: 140,
        }, {
            id: 'frequency',
            content: '触发频率次数',
            align: 'right',
            minWidth: 140,
        },
        {
            id: 'insideDays',
            content: '内部调整天数',
            align: 'right',
            minWidth: 140,
        },
    ];
    private tableDataResult: any[] = []; // 静态结果表数据
    private hasSelectedData: any[] = []; // 静态结果勾选数据

    ColumnUtil = new ColumnUtil();
    private staticResultQueryDialogVO: DialogVO = new DialogVO(); // 查询请求弹框

    // 信达默认导出顺序
    FSCINDAExportColumn: any[] = [
        { id: 'resultId', content: '序号' },
        { id: 'triggerType', content: '触险类型' },
        { id: 'tradeDate', content: '估值日期' },
        { id: 'prohibitionDate', content: '连续违规天数' },
        { id: 'triggerDay', content: '连续预警天数' },
        { id: 'dictFundCodes', content: '产品代码(名称)' },
        { id: 'entryCode', content: '条目编号' },
        { id: 'entryName', content: '风险说明' },
        { id: 'result', content: '计算结果(单位)' },
        { id: 'thresholdValue', content: '条目触发值' },
        { id: 'dictStockCodes', content: '证券代码(名称)' },
        { id: 'branchValues', content: '分支值' },
        { id: 'numerator', content: '分子值' },
        { id: 'denominator', content: '分母值' },
        { id: 'investBalance', content: '可投余量' },
        { id: 'legalDays', content: '法定调整天数' },
        { id: 'insideDays', content: '内部调整天数' },
        { id: 'frequency', content: '触发频率次数' },
        { id: 'controlGrade', content: '风险等级' },
        { id: 'resultInformation', content: '结果信息' },
        { id: 'calculateDate', content: '计算日期' },
    ];

    async mounted() {
        await this.getShowErrorType();
        this.historyColumns.forEach(ele => {
            if (ele.id == 'errorMessage') {
                ele.show = this.showErrorType;
            }
        });
        this.historyColumns = this.historyColumns.filter((item: any) => item.show !== false);
        this.columns = this.ColumnUtil.handleColumns(this.columns, 'id', 'resultId', this.historyColumns, true);
        await this.queryLayout();
        this.pageQuery(1);
    }

    // 查询静态是否展示错误类型
    async getShowErrorType() {
        let values = getSystem() || [];
        if (!getSystem().length) {
            await new Promise((resolve, reject) => {
                this.$axios
                    .get('/systemParam/list')
                    .then((res: any) => {
                        values = res;
                        resolve(res);
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        }
        let param;
        // 静态结果页面是否查询错误类型，1-开启，0-关闭
        param = values.find(item => item.paramKey == 'STATIC_REPORT_IS_ERROR_TYPE')?.paramValue;
        if (!param) {
            this.showErrorType = false;
            return;
        }
        if (param == '0') {
            this.showErrorType = false;
        } else if (param == '1') {
            this.showErrorType = true;
        }
    }
   // 静态结果分页
    private currentChange(val): void {
        this.page1.total = val.length;
    }

    getPage(val) {
        this.page1.total = val.length;
       return getCurrentPageData(val, this.page1.currentPage, this.page1.pageSize);
    }

    // 结果分页
    private pageQuery(currentPage?: number): void {
       let entryCode = this.transToResultDetail.entryCode;
        let fundCode = this.transToResultDetail.fundCode;
        let calculateDate = this.transToResultDetail.calculateDate;
        let tradeDate = this.transToResultDetail.tradeDate;
        this.staticResultReqVO.entryCodes = [entryCode];
        this.staticResultReqVO.reFundCode = [fundCode];
        this.staticResultReqVO.calculateDateStart = calculateDate;
        this.staticResultReqVO.calculateDateEnd = calculateDate;
        this.staticResultReqVO.tradeDateStart = tradeDate;
        this.staticResultReqVO.tradeDateEnd = tradeDate;
        const url = !this.isHistory ? '/static/fscinda/result/list' : '/static/fscinda/history/result/list';
        this.tableDataResultLoading = true;
        currentPage && (this.page.currentPage = currentPage);
        this.$axios
            .post(url, {
                ...this.staticResultReqVO,
                paging: {
                    currentPage: this.page.currentPage,
                    pageSize: this.page.pageSize,
                },
            })
            .then((res: any) => {
                if (this.showErrorType) {
                    this.tableDataResult = res;
                } else {
                    this.tableDataResult = res.filter(item => item.triggerType != '4');
                }
                this.page.total = res.length;
                this.tableDataResultLoading = false;
                this.fieldKey++;
            })
            .catch(() => {
                this.tableDataResultLoading = false;
            });
    }

    /**
     * 表头排序(静态结果)
     */
    handleSort(column: any) {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        const sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        let sort = '';
        const property = column.property;
        if (sortType) {
            if (property == 'entryCode') {
                if (sortType == 'DESC') {
                    sort = "DECODE(INSTR(C_ENTRY_CODE,'YH'),1,1,0) DESC,TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) DESC";
                } else {
                    sort = "DECODE(INSTR(C_ENTRY_CODE,'YH'),1,1,0) DESC,TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) ASC";
                }
            } else if (property === 'calculateDate') {
                if (sortType == 'DESC') {
                    sort = 'D_CAL_DATE DESC, D_CAL_TIME DESC';
                } else {
                    sort = 'D_CAL_DATE ASC, D_CAL_TIME ASC';
                }
            } else {
                sort = this.sortParamObj[property] + ' ' + sortType;
            }
        }
        this.staticResultReqVO.sort = sort;
        this.pageQuery(1);
    }

    // 导出
    private loadout(): void {
        let data = this.hasSelectedData;
        if (this.hasSelectedData.length < 1 || !this.hasSelectedData) {
            // this.$message.warning('请先勾选导出的数据');
            // return;
            data = [];
        }
        // 信达默认导出顺序
            this.$confirm('是否下载文件?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info',
            }).then(() => {
                if (!this.isHistory) {
                    const url = '/static/fscinda/result/export';
                    this.staticResultReqVO.exportKeys = XEUtils.map(data, item => item.resultId);
                    downLoadFile({
                        url: url,
                        method: 'post',
                        data: { ...this.staticResultReqVO },
                    });
                } else {
                    this.staticResultReqVO.exportKeys = XEUtils.map(data, item => item.resultId);
                    this.$axios.post('/static/fscinda/history/result/export', { ...this.staticResultReqVO }).then((res: any) => {
                        this.$emit('updateActiveTab', 'third');
                    });
                }
            });
    }

    // 结果刷新
    private refreshStatic(): void {
        this.hasSelectedData = [];
        this.pageQuery(1);
    }

    // 查询
    private queryStatic(): void {
        const title = !this.isHistory ? '静态结果高级查询' : '静态历史结果高级查询';
        this.staticResultQueryDialogVO = this.staticResultQueryDialogVO.getAddDialog(title);
    }

    // 高级查询返回值
    private staticResultQueryReturn(val): void {
        this.staticResultReqVO = val;
        this.pageQuery(1);
    }

    // 详情
    private handleRowOperateLook(row): void {
      //  const isHistory = this.activeValue === 'second';
        const isHistory = this.isHistory;
        this.$emit('handleRowOperateLook', { row, isHistory });
    }

    // 走势图
    private handleRowOperateChart(row): void {
        this.$emit('handleRowOperateChart', row);
    }

    // 全选
    private selectAllValueEvent({ selection }): void {
        this.hasSelectedData = selection;
    }

    // 部分勾选
    private selectValueChangeEvent({ selection }): void {
        this.hasSelectedData = selection;
    }

    /* **************************** 布局设置start ***************************** */
    layoutDialog: boolean = false; // 试算结果表布局设置
    showFieldList: any[] = []; // 要显示的表格列
    selectedFieldList: any[] = []; // 已选择字段列表
    fixedFieldList: any[] = []; // 固定字段列表
    tableDataResultNumKey: number = 1; // 静态结果Key
    fieldKey: number = 1;
    // 获取页面布局信息
    async queryLayout() {
        let url = 'RISK_RES';
        let columns = this.columns;

        if (this.isHistory) {
            url = 'RISK_RESULT_H';
            columns = this.historyColumns;
        }
        const resList: any = await new Promise((resolve, reject) => {
            getTableLayout(url)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        console.log(resList, 'resList');
        if (resList) {
            let list: any;
            console.log(list, 'list');

            try {
                list = JSON.parse(resList);
            } catch (err) {
                list = resList;
            }
            this.selectedFieldList = [];
            list.forEach(ele => {
                const obj = columns.find(item => item.id == ele.id);
                obj && this.selectedFieldList.push(obj);
            });
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        } else {
            this.showFieldList = columns;
            this.selectedFieldList = columns;
        }
        this.tableDataResultNumKey++;
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    /* **************************** 布局设置END ***************************** */

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    getAlign(ele: any) {
        let obj = this.columns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'left';
    }

    // 格式化产品代码
    private formatDictFundCodes(cellValue): string {
        let valueStr = XEUtils.map(cellValue, item => {
            if (item) {
                return item.dictKey + '(' + item.dictKeyName + ')';
            } else {
                return '--';
            }
        });
        return valueStr.toString();
    }

    formatAssetCodes(cellValue) {
        let retData = [];
        cellValue &&
            cellValue.map(key => {
                let name = (this.assetList.find(item => item.assetCode == key) || {}).assetName;
                retData.push(`${key}(${name})`);
            });
        return retData.toString() || '--';
    }

    formatFdAcCodes(cellValue) {
        let retData = [];
        cellValue &&
            cellValue.map(key => {
                let name = (this.fdAcList.find(item => item.fundAccountCode == key) || {}).fundAccountName;
                retData.push(`${key}(${name})`);
            });
        return retData.toString() || '--';
    }
}
</script>
<style lang="scss" scoped>
// tabs主内容
.container {
    padding: 0 20px 20px 20px;
    .header-container {
        border: 1px solid #ccc;
    }
    .dataInfo {
        margin-top: 10px;
    }
    .display-grid1 {
        display: grid;
        grid-template-columns: 25% 25% 25% 25%;
        height: 40px;
    }
    .display-grid2 {
        display: grid;
        grid-template-columns: 50% 50%;
        height: 40px;
    }
    .backGC {
        background-color: #f7f7f7;
        width: 100%;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
        width: 100% !important;
    }
    .boxStyle {
        margin: 40px 0 0 10px;
        width: 40px;
        height: 40px;
    }
    .iconStyle {
        color: #939398;
        font-size: 22px;
    }
}
/deep/ .vxe-table--render-default .vxe-table--expanded .vxe-table--expand-btn {
    font-size: 20px;
}

/deep/ .vxe-table--render-default .vxe-body--expanded-cell {
    margin-left: 49px;
    padding: 0;
}

/deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
    height: calc(100vh - 210px);
    min-height: 0;
 //   overflow-x: hidden;
}

.expand-wrapper {
    padding-bottom: 6px;

    /deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
        overflow: auto;
        max-height: calc(100vh - 315px);
        height: fit-content;
        min-height: 70px;
    }
}
</style>
<style lang="scss">
.tips-popper {
    max-width: 700px;
    max-height: 300px;
    overflow: auto;
}
</style>
